#include "Log.h"

int mylog(char * optional_msg,char * msg, int level)  
{  
    char * pc_level=getenv("LEVEL");  
    char * pc_path =getenv("LOGPATH");  
      
    //configure debug level  
    if(pc_level==NULL)    
    {     
        pc_level="WORKKING";  
    }  
    //printf("current level is  %s\n",pc_level);  
          
    //configure path      
    char path[256];  
    if(pc_path==NULL)  
    {         
        getcwd(path, sizeof(path));  
        //printf("current path is %s\n",path);  
        pc_path=path;     
                  
    }  
      
    //printf("configured path is %s\n",pc_path);      
      
    int int_src=0;  
    char *pc_preLog;  
    if(strcmp(pc_level,"DEBUG")==0)  
    {     
        int_src=5;  
        pc_preLog="[DEBUG]  ";  
    }  
    if(strcmp(pc_level,"WARNNING")==0)  
    {  
        int_src=4;  
        pc_preLog="[WARNNING]  ";  
    }  
    if(strcmp(pc_level,"ERROR")==0)  
    {  
        int_src=3;  
        pc_preLog="[ERROR]  ";  
    }  
    if(strcmp(pc_level,"WORKKING")==0)  
    {  
        int_src=1;  
        pc_preLog="[WORKKING]  ";  
    }  
      
    //create a file to write log.     
    char target_path[400];  
    strcpy(target_path,pc_path);  
    strcat(target_path,"/log.txt");  
    //printf("target path is %s\n",target_path);  
      
      
    if(int_src>=level)  
    {  
        int fileid=open(target_path,O_WRONLY|O_APPEND|O_CREAT,0);  
        if(fileid<0)  
        {  
            printf("create log file failed!\n");  
            exit(0);      
        }  
        write(fileid,optional_msg,strlen(optional_msg));  
        write(fileid,pc_preLog,strlen(pc_preLog));  
        write(fileid,msg,strlen(msg));  
        //set time  
        time_t timep;  
        time (&timep);  
        write(fileid,"   ----",strlen("   ----"));  
        write(fileid,ctime(&timep),strlen(ctime(&timep)));  
          
        write(fileid,"  \n",strlen("  \n"));  
        close(fileid);  
    }  
    return 0;  
}    

